<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi;

/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */

class studenController extends AdminController {

    static protected $allow = array( 'updatePassword','updateNickname','submitPassword','submitNickname');

    public function forecastReg() {

        $list   = $this->lists('ForecastReg', $map);

        $this->assign('_list', $list);
        $this->meta_title = '预登录的手机号信息';
        $this->display();

    }

    public function deleForecastReg() {
 
      
       if (!($phone=$_GET['phone'])) return false;
       $statu = M('ForecastReg')->where("phone='{$phone}'")->delete() ;
       if( $statu!==false ) {
            $this->success("提交成功",null,1);
        }else{ 
            $this->error("提交失败！",null,1);
        }  
    }
    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
      
        header('Cache-Control:no-cache,must-revalidate');  
        header('Pragma:no-cache');  
         $inputData =  I(); 
  
        if ($inputData['action']=='import')   {
             $this->assign('import', 1);
        }   
        $nickname = I('nickname');
        if ($inputData['time-start'])  {
                 $map['registered_time'] = array("EGT",strtotime($inputData['time-start']." 0:0:0"));
          };
        if ($inputData['time-end'])  { 
               $reg_time2 = array("ELT",strtotime($inputData['time-start']." 23:59:59")); 
               $map['registered_time'] = array($map['registered_time'],$reg_time2);
        };
        if ($inputData['fullname'])  { $map['fullname'] = array("LIKE",$inputData['fullname']."%"); };
        if ($inputData['telephone'])  { $map['telephone'] = array("LIKE",$inputData['telephone']); };
        unset($map['time-start'],$map['time-end']);

        if (IS_ROOT && false!=$inputData['queryRole'] ) {

            $studen_rows = getsql("select studen_id from ot_menber_bind_tag where member_uid in(".$inputData['queryRole'].")");
         
            foreach ($studen_rows as $studen) {
                $s_arr[] = $studen['studen_id'];
            }
 
            $map['id'] = array('in', implode(",", $s_arr) );
        }

         //活动类型
         if (false!=$inputData['active_type'] ) {
            $map['active_type'] = $inputData['active_type'];
         }
          //is_effective，是否有效
         if (false!=$inputData['is_effective'] ) {
            $map['is_effective'] = $inputData['is_effective'];
         }
        
         //
         if (!IS_ROOT) {
            // 如果不是管理员，只显示自己标注的会员记录
            //  $map['active_type']  = UID;
            $sql  = "SELECT studen_id FROM `ot_menber_bind_tag` WHERE member_uid='".UID."'";
            $studen_rows = getsql($sql);
 
            foreach ($studen_rows as $studen) {
                $studen_id_arr[] = $studen['studen_id'];
            }
            
            if ($studen_id_arr) $map_string_ids[]  = "id in (".implode(",", $studen_id_arr) .")" ;
  //prt($map_string_ids,0);
        }

     
        if ($inputData['id']) {
            //查询用户id
            $sql  = "SELECT id FROM `ot_studen` WHERE id='{$inputData['id']}' ";
            $memberRes = getsql($sql);
            foreach ($memberRes as $studen) {
                $studen_id_arr2[] = $studen['id'];
            }
            if ($studen_id_arr2) $map_string_ids[]  = "id in (". implode(",", $studen_id_arr2).")"  ;
 // prt($map_string_ids,0);
        }

 
        if (  is_numeric($inputData['intention']) ) {
            //意向
            $map['intention'] = $inputData['intention'];
        }
  
        if (is_numeric($inputData['accesslog'])) {
            //意向
            if ($inputData['accesslog']==1) {
                //已经回访
                //$map['_string'] = ' id in (SELECT studen_id FROM ot_studen_visit) ';
                $map_string_ids[] = ' id in (SELECT studen_id FROM ot_studen_visit) ';
 // prt($map_string_ids,0);             
            } else {
                //未回访
                $map_string_ids[] = ' id not in (SELECT studen_id FROM ot_studen_visit) ';
            }
  //prt($map_string_ids,0);
        }

        if ($map_string_ids) {
            $map['_string'] = implode(" and ",$map_string_ids);
        }

        $list   = $this->lists('Studen', $map);
 
 //prt(M('Studen')->getLastSql());
 //
        foreach ($list as $key => &$value) {
 
            if (false!=$value['birthday']) {
                $value['birthday'] = date("Y-m-d",$value['birthday']) ;
            } else {
                $value['birthday'] =  '';
            }
            false == $value['telephone']  && $value['telephone']='';
            false == $value['registered_time']  && $value['registered_time']='';
            if ($value['generation']) {
                $arr_generation = C("generation");
                $value['generation_name'] = $arr_generation[$value['generation']];
            }
            if ($value['grade']) {
                $arr_grade = C("grade");
                $value['grade_name'] = $arr_grade[$value['grade']];
            }
            
            if ($value['admin_work_code']) {  
                $value['admin_name'] = M("member")->where("work_code={$value['admin_work_code']}")->getField('nickname'); 
            }

            if ($value['sex']=='') {
                 $value['sex']='';
            } else {
                if (intval($value['sex']) == 1) { $value['sex']='男'; } else { $value['sex']='女'; }
            }
                         
            //access_info
            if (false == $value['access_num']) {
                $value['access_info'] = "未回访,<a href=".U('studen/accesslog',array("sid"=>$value['id'])).">回访</a>";
            } else {
               // $visitRes = M('studen_visit')->where("studen_id='{$value['id']}'")->field('visit_next_time')->order("id desc")->select();
              //  $visitRes = $visitRes[0];

                $value['access_info'] = "回访{$value['access_num']}次";
                $value['access_info'] .= ",<a href=".U('studen/accesslog',array("sid"=>$value['id']) ).">回访</a>";
            }

            $sql = "SELECT b.`member_uid`,b.`studen_id`,m.`nickname`,b.`u_type`,b.`bind_id`
                FROM `ot_member` m INNER JOIN  `ot_menber_bind_tag` b
                ON (m.`uid` = b.`member_uid`)  WHERE b.`user_status`=TRUE and b.`studen_id`='{$value['id']}' order by u_type asc";
            $res2 = getsql($sql);
            $bindArr = array();
            foreach ($res2 as $key2 => $value2) {
                $bindArr[$value2['u_type']] = array("nickname"=>$value2['nickname'],"bind_id"=>$value2['bind_id']);
            }
            if ($bindArr) {
                $value['bindList'] = $bindArr;
            }  

        }       
        
        $query_select_role_member = $this->getSelectRoleMember(1,'queryRole','queryRole'); 
        $this->assign('select_active_type',$this->get_active_type());
        $this->assign("query_select_role_member",$query_select_role_member) ;
        $where = "uid =". UID ;
        $u_type_row = getrow("SELECT `u_type` FROM `ot_member` WHERE ( $where  ) LIMIT 1 ");
  //prt($_SERVER['REQUEST_URI']);
        session('lastUrl',$_SERVER['REQUEST_URI']);
         
        $this->assign("myRole", $u_type_row['u_type'] ) ;
        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }
 
    //修改状态
    public function changeStatus(){
        $id = I('id');
        $this->editRow('Studen',array("is_effective"=>"$id","status"=>I('status')) );
    }


    public function editview(){
        $id = I('id');
        if ($id) {
            $where['id'] = $id;
            $row = M('studen')->where($where)->find();
         
            $this->assign('row',$row); 
 
        } else {
            $row['is_effective'] = 1;
            $this->assign('row',$row); 
        }
 
        $this->assign('select_active_type',$this->get_active_type());
        $this->assign('_grade', C('grade')) ;
        $this->assign('_generation', C('generation'));
        $this->display(); 
    }

    public function save() {
        $post =I('post.');
        $msg = $this->checkData($post);
        if ($msg !==1 ) {
            $this->error($msg,null,1);
            exit;
        }
 
        if (!$post['id']) {

            $res = M('studen')->add($post);
        } else {
            $where['id'] = $post['id'];
            $res = M('studen')->where($where)->save($post);
        
        }
        if( $res!==false ) {
            $url = U("admin/studen/index");
            $this->success("提交成功",$url,1);
        }else{ 
            $this->error("提交失败！",null,1);
        }      
    }

    private function checkData(&$param) {
        if (!$param['fullname']) {
            return "用户名必须输入";
        }
        $param['fullname']=safety_html($param['fullname']);
 
        if (false==$param['telephone'] && false==$param['id']) {
            //新增记录，才要输入电话
            return "联系电话必须输入";
        }

        if (false!=$param['telephone']) {
            $tel=$param['telephone'];
            $isMob="/^1[3-5,7,8]{1}[0-9]{9}$/";
            $isTel="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
            if(!preg_match($isMob,$tel) && !preg_match($isTel,$tel))
            {
                return'手机或电话号码格式不正确。如果是固定电话，必须形如(xxxx-xxxxxxxx)!';
            }
        }
/*
        if ($param['is_effective']==0 && $param['invalid_memo']==false ) {
            return "无效记录要输入原因！";
        }
        */
        if ($param['is_effective']==1) $param['invalid_memo']='';

        if (false ==$param['id']) unset($param['id']);
        $param['createdTime'] = time();
        $param['member_uid'] = UID;

        return 1;

    }

    public function accesslog() {
        if(!IS_ROOT){
            
            //$map['member_uid'] = UID;
        }

        $sid =I('sid');
        $sql = "select fullname,id as sid FROM ot_studen where id='{$sid}'";
        $data  = getsql($sql);
        $this->assign("row",$data[0]);

 
        $where = "o.id='{$sid}'";
        $sql = "SELECT o.`fullname`,v.*,v.id as visit_id,m.nickname as admin_name  FROM `onethink`.`ot_studen_visit` v  INNER JOIN `ot_studen` o  ON (v.`studen_id` = o.`id`)  INNER JOIN `ot_member` m  ON (m.`uid` = v.`admin_id`)   where 1 and $where order by visit_updatetime desc ";
         
        $datalist = getsql($sql);
       
        foreach ($datalist as $key => &$value) {
            if ($value['trial_time']) {
                $value['trial_time'] = date("Y-m-d",$value['trial_time']);
            } else {
                $value['trial_time'] = '';
            }
        }
  
        $this->assign("_datalist",$datalist);
        $this->display();
        
    }

    //保存回访日志
    public function access_save() {
        $post =I('post.');
 
        if ($post['is_trial']) {
            $data['is_trial'] = 1;
            $data['trial_time'] = strtotime($post['trial_time']);
        }       
        $data['studen_id'] = $post['sid'];
        $data['admin_id'] = UID ;
        $data['visit_conter'] = $post['visit_conter'];
        $data['visit_updatetime'] =  time() ;
        $data['visit_next_time'] = strtotime($post['visit_next_time']);
        $data['visit_remark'] = $post['visit_remark'];
        $res = M('studen_visit')->add($data);
        if (false==$res) {
            die(json_encode(array("status"=>'false',"msg"=>"提交失败！")));
        } else {
            //`ot_studen`  access_num  access_lasttime
            $count = M('studen_visit')->where("studen_id={$post['sid']}")->count();
            if ($count>0) {
                $first = M('studen_visit')->where("studen_id={$post['sid']}")->order('id desc')->limit(1)->select();
                $studenSave= array();
                $studenSave['id'] =  $data['studen_id'];
                $studenSave['access_num'] =  $count;
                $studenSave['access_lasttime'] =  $first[0]['visit_updatetime'];
                M('studen')->save($studenSave);
            }
            //die(json_encode(array("status"=>'success',"url"=>U('studen/index'))));
            //
            die(json_encode(array("status"=>'success',"url"=>session('lastUrl'))));
        }
    }

    public function deleteUser() {
        $post =I('post.');
        if (false==$post)   {
             die(json_encode(array("status"=>'false',"msg"=>"提交失败！")));
        }
  
        foreach ($post['id'] as $key => $value) {
            $ids[] = "'".$value."'" ; 
        }

        //是否绑定给客户经理
        $phone_bind_member_Model = M('phone_bind_member'); 
        $has_BindRow = $phone_bind_member_Model->where('studen_id in ('.implode(",", $ids).")")->count();
        
        if ($has_BindRow) {
            die(json_encode(array("status"=>'false',"msg"=>"记录内有已经分配的数据,不能删除记录！")));  
        }  

        $res = M('studen')->where('id in ('.implode(",", $ids).')')->delete();
        
        if (false==$res) {
            die(json_encode(array("status"=>'false',"msg"=>"提交失败！")));
        } else {
            die(json_encode(array("status"=>'success' )));
        }
    }

   
    public function getphone() {
        if (!$_POST['telephone']) die('error');
        $sql = "select count(*) as total from ot_studen where telephone='{$_POST['telephone']}'";
        $row = getrow($sql);
        if ($row['total']>0) {
            die('telephone_has');
        } else {
            die('telephone_add_ok');
        }

    }
	
	public function doImport() {
        session('improt_info',null);
		if ($_FILES['error']>0) {
            $this->error("读取文件失败",null,1);
            return false;
		}
		$filename = $_FILES['upfile']['tmp_name'];
		$csvRes = $this->readfile_chunked($filename);
 
        if( $csvRes ==false  ) {
           $this->error("读取文件失败或文件无内容",null,1);
           return false;
        } 
 
        $mdl = M('studen');
        $mdl->startTrans();
        $import_y = 0;
        $improtErrArr = array();
        //1孩子姓名,2性别, 3年级,4联系电话,5家长姓名,6家长身份,7家庭住址,8所在学校,9内部人员,10来源
 
        for ($x=1;$x<count($csvRes);$x++) {
 
            if ($csvRes[$x]) {
                $row = $csvRes[$x];
                $post = explode(",", $row);
 
                $save = array();
                $save['fullname'] = $post[0]?iconv('gb2312', 'utf-8', $post[0]):'';  
                $save['sex'] = $post[1]?(iconv('gb2312', 'utf-8', $post[1])=='男'?1:0):'';
                $save['generation'] = $post[2]?iconv('gb2312', 'utf-8', $post[2]):''; //
                $save['grade'] = $post[3]?iconv('gb2312', 'utf-8', $post[3]):''; //
                $save['telephone'] = $post[4];
                $save['parents'] = $post[5]?iconv('gb2312', 'utf-8', $post[5]):''; //
                $save['parents_appellative'] = $post[6]?iconv('gb2312', 'utf-8', $post[6]):''; //
                $save['homeaddress'] = $post[7]?iconv('gb2312', 'utf-8', $post[7]):''; //
                $save['school'] = $post[8]?iconv('gb2312', 'utf-8', $post[8]):''; //
                $save['registered_time'] =  time();
                $save['remark'] = $post[11]?iconv('gb2312', 'utf-8', $post[11]):''; //remark备注
                //验证手机号
                $msg = $save;unset($msg['registered_time']);
                $rec_str = "导入记录：".implode(";",$msg).";"; unset($msg); 
                if (  !preg_match("/\d+$/", $save['telephone'])   ) { 
                     
                    $improtErrArr[]=  $rec_str."导入的手机号不能为空或格式非法" ;
                    continue;

                }
  
                //开始导
                    $res = $mdl->add($save);
                    if (false==$res) {
 
                        $improtErrArr[]=  $rec_str."导入文件失败，".$mdl->getDbError()  ;
                        continue;

                    } else {
                        $import_y++;
                        $mdl->commit();//提交
                    }

                    $newID = mysql_insert_id();
                    //处理环节1，来源， 内部分员分配 
                     if ($post[9]) { //内部分员分配
                            $memberRow = $this->getTap($post[9]);   //内部分员分配
             
                            $source =  iconv('gb2312', 'utf-8', $post[10]); //分配给外线人员，称为来源

                            if (!$memberRow) {
                                $improtErrArr[]=  $rec_str."未找到内部人员记录，请在用户/用户信息内/新增" ;
                                continue;
                            }

                            //成功后绑定tag
                            $memberRow['student_id'] = $newID;
                            $saveRes = $this->saveAlloc($memberRow);
                            if (isset($saveRes['error'])) {
                                $improtErrArr[]=  $rec_str.$saveRes['error'] ;
                                continue;
                            }
                    }
                    //处理环节2，来源， 分配给外线人员，称为来源 ----------------
                     if ($post[10]) { 
                        $sourceRow = $this->getTap($post[10]);   //内部分员分配                        
                        if (!$sourceRow) {
                            $improtErrArr[]=  $rec_str."未找到内部人员记录，请在用户/用户信息内/新增" ;
                            continue;
                        }
                        $sourceRow['student_id'] = $newID;
                        $saveRes = $this->saveAlloc($sourceRow);
                        if (isset($saveRes['error'])) {
                            $improtErrArr[]=  $rec_str.$saveRes['error'] ;
                            continue;
                        }
                    }
            } 
        }

        
        $improtErrArr[] = "共计记录：".(count($csvRes)-1).",成功导入{$import_y}条，失败".(count($csvRes)-1-$import_y)."条";
		session('improt_info', implode("\r\n",$improtErrArr)  ); 
        $this->success("导入完成","/index.php?s=/admin/studen/index.html&action=import",1); 
        
	}
	
    private function saveAlloc($row){
        //绑定处理
        $menber_bind_tag_Model = M('menber_bind_tag'); 

        $data = array();
        $data['studen_id'] = sprintf("%08d", $row['student_id']);// 不足8位数，前置补零
        $data['member_uid'] = $row['uid']; 
        $data['u_type'] = $row['u_type']; 
        $data['create_time'] = time();
        
        $count = $menber_bind_tag_Model->where(array('studen_id'=>$row['studen_id'],'u_type'=>$row['u_type']))->count();
        $menber_bind_tag_Model->startTrans();
        if ($count ==0) {
            try {
                $menber_bind_tag_Model->add($data); // 根据条件保存修改的数据   
            }catch(Exception $e) {
                   $menber_bind_tag_Model->rollback();//不成功，回滚
                   $this->error($e->getMessage(),null,1); 
                   return false;
            }  
            $menber_bind_tag_Model->commit();      
        } else {
           return array("error"=>"发现有数据已经分配,不能对已经分配的数据操作");
        }               
    }
    


    private function getTap($name) {
        if (false ==$name) { return false ; }
        $name = iconv('gb2312', 'utf-8', $name); //
        $memberRes = getsql("SELECT * FROM `ot_member` WHERE ( nickname='{$name}' ) LIMIT 1 ");

        return $memberRes[0]?$memberRes[0]:false;

    }
	private function readfile_chunked($filename) { 
	   $chunksize = 1*(1024*1024); // how many bytes per chunk 
	   $buffer = ''; 
	   $cnt = ''; 
	   // $handle = fopen($filename, 'rb'); 
	   $handle = fopen($filename, 'rb'); 
	   if ($handle === false) { 
		   return false; 
	   } 
	   while (!feof($handle)) { 
		   $buffer = fread($handle, $chunksize); 
		   //echo $buffer; 
		   ob_flush(); 
		   flush(); 
		   
			if ($buffer) $cnt  .= $buffer; 
		    
	   } 
       $data = explode("\r\n", $cnt);
       foreach ($data as $key => $value) {
           if (!$value) unset($data[$key]);
       }
	   $status = fclose($handle); 
	   
		return $data;
	}

 
    public function sesslog(){
        $filename = DATA_PATH."sendsms_all.txt";
       
        $handle = fopen($filename, "r");
        $contents = fread($handle, filesize ($filename));
        fclose($handle);


        $this->assign('contents',$contents) ;        
        $this->display(); 
    }
    //预约试听
    public function trial(){

        $sql = "select count(id) as total from ot_studen where id in (
                select studen_id from ot_studen_visit where is_trial=1
                )";
        if (!IS_ROOT) {
            $sql2= "select studen_id from ot_menber_bind_tag where member_uid = ".UID;
            $sql .= "  and id in ($sql2)";
        }

        $row = getrow($sql);
        $this->assign('total',$row['total']) ;  
        ///
        $today = date("Y-m-d");
        $sql = "select * from ot_studen_visit where FROM_UNIXTIME(`trial_time`,'%Y-%m-%d')='{$today}'";
        if (!IS_ROOT) {
            $sql2= "select studen_id from ot_menber_bind_tag where member_uid = ".UID;
            $sql .= "  and studen_id in ($sql2)";
        }
 
        $visitRows = getsql($sql);
        foreach ($visitRows as $key => &$value) {
           $value['fullname'] = M('Studen')->where("id='{$value['studen_id']}'")->getField('fullname');
           $value['telephone'] = M('Studen')->where("id='{$value['studen_id']}'")->getField('telephone');
           $value['trial_time'] = $value['trial_time']==0?'':date('Y-m-d',$value['trial_time']);
        }
        $this->assign('todayRows',$visitRows) ;  
        ////
        $map['is_trial']=1; 
        $map['_string'] =" FROM_UNIXTIME(`trial_time`,'%Y-%m-%d') != '{$today}' ";
        if (!IS_ROOT) {
            $sql2= "select studen_id from ot_menber_bind_tag where member_uid = ".UID;
            $sql_string = "  and id in ($sql2)";
            $map['_string'] .= $sql_string;
        }
        
        $list   = $this->lists('StudenVisit',$map,"trial_time desc");
       

        foreach ($list as $key => &$value) {
           $value['fullname'] = M('Studen')->where("id='{$value['studen_id']}'")->getField('fullname');
           $value['telephone'] = M('Studen')->where("id='{$value['studen_id']}'")->getField('telephone');
           $value['trial_time'] = $value['trial_time']==0?'':date('Y-m-d',$value['trial_time']);
        }
        $this->assign('_datalist',$list) ;  

       
        $this->display(); 
    }
}
